package c.x.jy.service.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import c.x.jy.common.utils.SysUtils;
import c.x.jy.dao.dto.MemberEntityDto;
import c.x.jy.dao.entity.MemberWalletEntity;
import c.x.jy.service.service.MemberWalletService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import c.x.jy.common.exception.RRException;
import c.x.jy.common.utils.PageUtils;
import c.x.jy.common.utils.Query;
import c.x.jy.dao.dao.MemberDao;
import c.x.jy.dao.entity.BusinessEntity;
import c.x.jy.dao.entity.MemberEntity;
import c.x.jy.service.redis.Cache;
import c.x.jy.service.service.BusinessService;
import c.x.jy.service.service.MemberService;
import c.x.jy.service.utils.MemberUtil;
import c.x.jy.service.utils.SpringContextUtils;
import org.springframework.transaction.annotation.Transactional;

@CacheConfig(cacheNames = { "member" })
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

	@Autowired
	private Cache redisUtils;
	@Autowired
	private BusinessService businessService;
	@Autowired
	private MemberWalletService memberWalletService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		QueryWrapper<MemberEntityDto> query = new QueryWrapper<MemberEntityDto>();
		if (params.get("searchKey") != null && params.get("searchValue") != null
				&& !StringUtils.isEmpty(params.get("searchKey").toString())
				&& !StringUtils.isEmpty(params.get("searchValue").toString()))
			query.eq(params.get("searchKey").toString(), params.get("searchValue"));
		if (params.get("businessId") != null)
			query.eq("business_id", params.get("businessId"));
//		IPage<MemberEntity> page = this.page(new Query<MemberEntity>().getPage(params), query);
		IPage<MemberEntityDto> page = this.getBaseMapper().querypage(new Query<MemberEntityDto>().getPage(params), query);

		return new PageUtils(page);
	}

	@Override
	@Transactional
	public MemberEntity saveOrUpdateByOpenid(MemberEntity customer) {
		MemberEntity cust = (SpringContextUtils.getBean(MemberServiceImpl.class)).getMemberByOpenId(customer.getOpenid());
		if (cust == null) {
			BusinessEntity b = businessService.selectBusinessByCode(MemberUtil.get().getBusinessCode());
			if (b == null || !b.getStatus().equals(1))
				throw new RRException("未找到代理", 2);
			customer.setBusinessId(b.getId());
			customer.setCreateDate(new Date());
			customer.setReferralCode(SysUtils.generateShortCode());
			if(!StringUtils.isEmpty(MemberUtil.get().getMcode()) ){
				MemberEntity parent=	baseMapper.selectByReferralCode(MemberUtil.get().getMcode());
				if(parent!=null)customer.setParentId(parent.getId());
			}
			baseMapper.insert(customer);

//			生成钱包数据
			MemberWalletEntity memberWalletEntity = new MemberWalletEntity();
			memberWalletEntity.setMemberId(customer.getId());
			memberWalletEntity.setBalance(new BigDecimal(0));
			memberWalletEntity.setTotalBalance(new BigDecimal(0));
			memberWalletEntity.setCommissionBalance(new BigDecimal(0));
			memberWalletEntity.setFrozenCommission(new BigDecimal(0));
			memberWalletEntity.setTotalCommission(new BigDecimal(0));
			memberWalletEntity.setScores(0);
			memberWalletEntity.setTotalScores(0);
			memberWalletEntity.setGiveBalance(new BigDecimal(0));
			memberWalletEntity.setSpendMoney(new BigDecimal(0));
			memberWalletEntity.setTotalGive(new BigDecimal(0));
			memberWalletService.save(memberWalletEntity);


		} else {
			customer.setEvalScore(null);
			customer.setEvalPeoplenum(null);
			customer.setAskPeoplenum(null);
			customer.setUpdateDate(new Date());
			customer.setBusinessId(null);
			customer.setHeadimgurl(null);
		 
			baseMapper.update(customer, new QueryWrapper<MemberEntity>().eq("openid", customer.getOpenid()));
			customer	= (SpringContextUtils.getBean(MemberServiceImpl.class)).getMemberByOpenId(customer.getOpenid());
		}

		removeMemberCache(customer);
		return customer;

	}

	@Cacheable(key = "'member:'+ methodName +':'+#p0  ", unless = "#result == null ")
	@Override
	public MemberEntity getMemberByOpenId(String openid) {
		MemberEntity member = null;
		if (member == null) {
			member = baseMapper.selectOne(
					new QueryWrapper<MemberEntity>().lambda().eq(MemberEntity::getOpenid, openid).last(" limit 1 "));
		}
		return member;
	}
    /**
     * 限微信端使用
     */
	@Override
	public MemberEntity getCurrUser() {
		return (SpringContextUtils.getBean(MemberService.class)).getMemberByOpenId(MemberUtil.get().getOpenid());
	}

	@Override
	public MemberEntity selectMemberByIdForUpdate(Long memberId) {
 
		return this.getBaseMapper().selectMemberByIdForUpdate(memberId);
	}

	@Override
	public MemberEntity selectByReferralCode(String referralCode) {
		QueryWrapper<MemberEntity> query=new QueryWrapper<>();
		query.lambda().eq(MemberEntity::getReferralCode, referralCode);
		return this.getBaseMapper().selectOne(query);
	}
	@Cacheable(key = "'member:'+ methodName +':'+#p0  ", unless = "#result == null ")
	@Override
	public MemberEntity getMemberByCacheById(Long memberId) {
		// TODO Auto-generated method stub
		return  this.getBaseMapper().selectById(memberId);
	}

	//清缓存
	//member::member:getMemberByOpenId:odsJd6WSSPKYjb07GswggrZNFJCM
	@Override
	public void removeMemberCache(MemberEntity customer) {
		redisUtils.remove("member:", "member:getMemberByOpenId:" + customer.getOpenid());
		redisUtils.remove("member:", "member:getMemberByCacheById:" + customer.getId());
	}

	@Override
	public Integer countmymyconnection(Long id) {
		QueryWrapper<MemberEntity> query=new QueryWrapper<>();
		query.lambda().eq(MemberEntity::getParentId,id);
		return this.getBaseMapper().selectCount(query );
	}

	@Override
	public List<MemberEntity> countmymyconnectionlist(Long id) {
		QueryWrapper<MemberEntity> query=new QueryWrapper<>();
		query.lambda().eq(MemberEntity::getParentId,id);
		return this.getBaseMapper().selectList(query );
	}
}
